package com.approval.service;

import com.approval.dto.OrgTreeNode;
import com.approval.entity.Org;
import com.approval.entity.User;
import com.approval.exception.BusinessException;
import com.approval.mapper.OrgMapper;
import com.approval.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 组织架构服务
 */
@Service
@Transactional
public class OrgService {
    
    @Autowired
    private OrgMapper orgMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 创建组织
     */
    public Org createOrg(Org org) {
        // 验证组织编码是否已存在
        if (orgMapper.selectByOrgCode(org.getOrgCode()) != null) {
            throw new BusinessException("组织编码已存在");
        }
        
        org.setCreateTime(new Date());
        org.setUpdateTime(new Date());
        orgMapper.insert(org);
        
        return org;
    }
    
    /**
     * 更新组织
     */
    public Org updateOrg(Long id, Org org) {
        Org existingOrg = orgMapper.selectById(id);
        if (existingOrg == null) {
            throw new BusinessException("组织不存在");
        }
        
        // 验证组织编码是否已被其他组织使用
        if (!org.getOrgCode().equals(existingOrg.getOrgCode())) {
            if (orgMapper.selectByOrgCode(org.getOrgCode()) != null) {
                throw new BusinessException("组织编码已被其他组织使用");
            }
        }
        
        org.setId(id);
        org.setUpdateTime(new Date());
        orgMapper.update(org);
        
        return org;
    }
    
    /**
     * 删除组织
     */
    public void deleteOrg(Long id) {
        Org org = orgMapper.selectById(id);
        if (org == null) {
            throw new BusinessException("组织不存在");
        }
        
        // 检查是否有子组织
        List<Org> children = orgMapper.selectByParentId(id);
        if (!children.isEmpty()) {
            throw new BusinessException("该组织下还有子组织，不能删除");
        }
        
        orgMapper.deleteById(id);
    }
    
    /**
     * 根据ID获取组织
     */
    public Org getOrgById(Long id) {
        return orgMapper.selectById(id);
    }
    
    /**
     * 获取所有组织
     */
    public List<Org> getAllOrgs() {
        return orgMapper.selectAll();
    }
    
    /**
     * 获取组织树
     */
    public List<OrgTreeNode> getOrgTree(Long deptId, String type) {
        List<OrgTreeNode> result = new ArrayList<>();
        
        if (deptId == null) {
            // 获取根组织
            List<Org> rootOrgs = orgMapper.selectRootOrgs();
            for (Org org : rootOrgs) {
                OrgTreeNode node = convertToOrgTreeNode(org);
                // 递归获取子节点
                buildOrgTree(node, org, type);
                result.add(node);
            }
        } else {
            // 获取指定部门本身及其子节点
            Org targetOrg = orgMapper.selectById(deptId);
            if (targetOrg != null) {
                OrgTreeNode node = convertToOrgTreeNode(targetOrg);
                // 递归获取子节点
                buildOrgTree(node, targetOrg, type);
                result.add(node);
            }
        }
        
        return result;
    }
    
    /**
     * 根据父组织ID获取子组织列表
     */
    public List<Org> getOrgsByParentId(Long parentId) {
        return orgMapper.selectByParentId(parentId);
    }
    
    /**
     * 获取活跃组织列表
     */
    public List<Org> getActiveOrgs() {
        return orgMapper.selectByStatus(1);
    }
    
    /**
     * 根据用户名搜索用户
     */
    public List<OrgTreeNode> searchUsersByName(String userName) {
        List<User> users = userMapper.selectWithConditions(userName, null, 1, 0, 100);
        return users.stream()
                .map(this::convertUserToOrgTreeNode)
                .collect(Collectors.toList());
    }
    
    /**
     * 将Org转换为OrgTreeNode
     */
    private OrgTreeNode convertToOrgTreeNode(Org org) {
        OrgTreeNode node = new OrgTreeNode();
        node.setId(org.getId());
        node.setName(org.getOrgName());
        node.setType("dept");
        node.setParentId(org.getParentId());
        node.setLevel(org.getLevel());
        node.setSortOrder(org.getSortOrder());
        node.setDescription(org.getDescription());
        node.setStatus(org.getStatus());
        node.setChildren(new ArrayList<>());
        return node;
    }
    
    /**
     * 将User转换为OrgTreeNode
     */
    private OrgTreeNode convertUserToOrgTreeNode(User user) {
        OrgTreeNode node = new OrgTreeNode();
        node.setId(user.getId());
        node.setName(user.getName());
        node.setType("user");
        node.setStatus(user.getStatus());
        node.setChildren(new ArrayList<>());
        return node;
    }
    
    /**
     * 递归构建组织树
     */
    private void buildOrgTree(OrgTreeNode parentNode, Org parentOrg, String type) {
        // 获取子组织
        List<Org> childOrgs = orgMapper.selectByParentId(parentNode.getId());
        for (Org childOrg : childOrgs) {
            OrgTreeNode childNode = convertToOrgTreeNode(childOrg);
            buildOrgTree(childNode, childOrg, type);
            parentNode.getChildren().add(childNode);
        }
        
        // 如果type参数包含user，则添加该部门下的用户
        if (type != null && (type.contains("user") || "user".equals(type))) {
            List<User> users = orgMapper.selectUsersByDepartmentCode(parentOrg.getOrgCode());
            for (User user : users) {
                OrgTreeNode userNode = convertUserToOrgTreeNode(user);
                parentNode.getChildren().add(userNode);
            }
        }
    }
}
